﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Configuration;
using IHISCETeim.BLL;


namespace IHISCETeim.SendSMSSvr
{
    public partial class AutoSendSMS : ServiceBase
    {
        public AutoSendSMS()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 获取周期时间
        /// </summary>
        /// <returns></returns>
        private int GetSnycInterval()
        {
            int SnycInterval = 0;
            try
            {
                SnycInterval = Convert.ToInt32(ConfigurationManager.AppSettings["SnycInterval"]);
            }
            catch
            {
                SnycInterval = 5;
            }
            return SnycInterval * 1000*60;
        }

        protected override void OnStart(string[] args)
        {
            Common.WriteLog("IHISCE信息化管理系统短信自动发送服务已启动!");
            timer1.Interval = GetSnycInterval();

            //timer1.Interval = 1000 * 10;
            timer1.Enabled = true;
            timer1.Start();
            ///启动定时处理短信内容程序
            timer2.Interval = 1000 * 60 * 60;
            timer2.Enabled = true;
            timer2.Start();
        }

        protected override void OnStop()
        {
            timer1.Enabled = false;
            timer1.Stop();

            timer2.Enabled = false;
            timer2.Stop();
            Common.WriteLog("信息化管理系统短信自动发送服务已停止!");
        }
        bool Exeed = false;
        /// <summary>
        /// 定时执行短信发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Common.WriteLog("开始扫描需发送短信");
            int statehour=8;
            int endhour=20;
            int nowhour=DateTime.Now.Hour;

            if (nowhour >= statehour && nowhour < endhour)
            {

                if (!Exeed)
                {

                    Exeed = true;
                    try
                    {
                        StartSend();
                    }
                    catch (System.Exception err)
                    {
                        Common.WriteLog(err.Message);
                        //SendSMSToAdmin(err.Message);
                    }
                    Exeed = false;
                }
            }
            Common.WriteLog("结束扫描需发送短信");
        }

        /// <summary>
        /// 开始执行短信发送程序
        /// </summary>
        private void StartSend()
        {
            string re= ProccessSysSMS.StateProccess();
            if (!string.IsNullOrEmpty(re))
                SendSMSToAdmin(re);
            //return;

            Common.WriteLog("=====查询短信余额==========================");
            string balance = SMSSendController.GetBalance();
            Common.WriteLog("=====查询短信余额[" + balance + "]条=======");
            Common.WriteLog("=====结束查询短信余额======================");

            DataTable sendDT = DAL.SMSList_GetNeedSendBySMSType("", false);
            Common.WriteLog("开始执行短信发送,本次需要发送短信[" + sendDT.Rows.Count.ToString() + "]条");
            //if (sendDT.Rows.Count <= 0)
            //    return;
            int suucesscount = 0, errorcount = 0;
           
            foreach (DataRow dr in sendDT.Rows)
            {
                Thread.Sleep(500);//休息0.5秒
                int ID =Convert.ToInt32(dr["ID"].ToString());
                string mobile = dr["Mobile"].ToString();
                string smsmessage = dr["SMSContent"].ToString();
                string stime = dr["NeedSendDate"].ToString();
                string SendType = dr["SendType"].ToString();
                string sendresult = "";
                stime = string.IsNullOrEmpty(stime) ? "" : stime;
                switch (SendType)
                {
                    case "单条发送":
                        sendresult = SMSSendController.SendSing(mobile, smsmessage, stime);
                        break;
                    case "多手机对一内容":
                        sendresult = SMSSendController.BatchSend(mobile, smsmessage, stime);
                        break;
                    case "多手机对多内容":
                        sendresult = SMSSendController.PersonalitySend(mobile, smsmessage, stime);
                        break;
                }

                if (sendresult == "")
                {
                    suucesscount++;
                    DAL.SMSList_Update(ID);
                }
                else
                {
                    errorcount++;
                    Common.WriteLog(string.Format("短信发送失败,失败原因:[" + sendresult + "].本次短信内容:mobile-->[{0}].smsmessage-->[{1}].stime-->[{2}].SendType-->[{3}]",mobile,smsmessage,stime,SendType));
                    
                    SendSMSToAdmin("StartSend方法:"+sendresult);
                }

            }
            Common.WriteLog(string.Format("结束短信发送.其中{0}条成功{1}条失败",suucesscount,errorcount));
            Common.WriteLog("---------------------------------------------------------------------------------");
        }

        /// <summary>
        /// 如果出问题就发送短信给管理员
        /// </summary>
        /// <param name="msg"></param>
        private void SendSMSToAdmin(string msg)
        {
            try
            {
                IHISCETeim.BLL.SEMailListController.AddAppError("IHISCE短信服务", "IHISCE短信服务", msg);
                //IHISCETeim.BLL.SMSProccessController.Add("程序报警", "15980907855", msg);
            }
            catch
            { 
                
            }
        }

        private void timer2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

        }
       
    }
}
